package com.msw.xml;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.FileInputStream;

/**
 * 使用javax原生api解析， XPath解析 xml文件包括node和attribute
 *
 * <p/>
 * Created by hadoop on 16-2-21.
 */
public class XPathParser {

    private static Document doc;
    private static XPath xpath;

    public static void main(String[] args) throws Exception {
        String rssXml = XPathParser.class.getResource("/rss.xml").getPath();
        init(rssXml);

        getAttrEles();

    }

    // 获取指定属性的元素
    // 获取所有大于指定价格的书箱
    public static void getAttrEles() throws XPathExpressionException {
        NodeList nodeList = (NodeList) xpath.evaluate("/rss/bookstore/book/title", doc,
                XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(nodeList.item(i).getNodeName() + "-->"
                    + nodeList.item(i).getTextContent() + "  " +
                    nodeList.item(i).getAttributes().getNamedItem("lang").getNodeValue());
        }
        System.out.println();
    }


    // 初始化Document、XPath对象
    public static void init(String xml) throws Exception {
        // 创建Document对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = db.parse(new FileInputStream(new File(xml)));

        // 创建XPath对象
        XPathFactory factory = XPathFactory.newInstance();
        xpath = factory.newXPath();
    }
}
